package de.kardass.jsmatep.in.tools;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import de.kardass.jsmatep.in.ImportProcessor;
import de.kardass.jsmatep.in.RecordMappingException;
import de.kardass.jsmatep.in.RecordToValueObjectMapper;
import de.kardass.jsmatep.in.validation.ConfigValidator;
import de.kardass.jsmatep.schema.jSmaTePImportConfig.JSmaTePImportConfigDocument;
import de.kardass.jsmatep.schema.jSmaTePImportConfig.RecordImportConfigType;
import de.kardass.jsmatep.util.ContentReader;
import de.kardass.jsmatep.util.IOUtil;

public class ImportFileValidator extends ImportProcessor<Object> {

	public ImportFileValidator(String configFileName) {
		super(configFileName);
	}

	public void validateFile(String importFileName) {
		try {
			final List<String> content = ContentReader.readContents(importFileName);
			validateContent(content);
		} catch (IOException e) {
			throw new RecordMappingException(e);
		}
	}

	public void validateContent(List<String> content) {
		InputStream in = null;
		try {
			in = IOUtil.getAsInputStream(getConfigFileName());
			final JSmaTePImportConfigDocument theDoc = JSmaTePImportConfigDocument.Factory.parse(in);
	      final RecordImportConfigType importConfig = theDoc.getJSmaTePImportConfig();
	      ConfigValidator.validateConfig(importConfig);
	      final RecordToValueObjectMapper<Object> mapper = new RecordToValueObjectMapper<Object>(importConfig);
			long lineCounter = 0;
			long recordCounter = 0;
			Object valueObject;
			for (String aRecord : content) {
				++lineCounter;
				try {
					if (ImportProcessor.skipContent(aRecord)) {
						// do nothing
					} else {
						++recordCounter;
						valueObject = instantiateNewValueObject(importConfig);
						valueObject = mapper.mapRecordToValueObject(aRecord, valueObject);
					}
				} catch (Exception e) {
					System.out.println("Error in line " + lineCounter);
					e.printStackTrace(System.out);
					System.out.println("##########");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			IOUtil.closeStream(in);
		}
	}

	public static void main(String... args) {
		if (args.length != 2) {
			usage();
			System.exit(-1);
		}
		final String configFile = args[0];
		final String importFile = args[1];
		System.out.println("Validate import file [" + importFile + "] with configuration [" + configFile + "]");
		new ImportFileValidator(configFile).validateFile(importFile);
		System.out.println("Finished!");
	}

	private static void usage() {
		System.err.println("Illegal arguments calling " + ImportFileValidator.class.getName());
		System.err.println(" call: java " + ImportFileValidator.class.getName() + " <xml-config-file> <data-import-file>");
	}

}
